package net.pugsplace.gpremacy.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import net.pugsplace.gpremacy.server.net.Connection;

public class Server implements Runnable {
	private static Logger log = Logger.getLogger(Server.class.getName());

	public static void main(String[] args) {
		try {
			File file = new File("logging.properties");
			if (file.canRead()) {
				System.out.println("Loading logging properties from " + file);
				LogManager.getLogManager().readConfiguration(new FileInputStream(file));
			}
		} catch (Exception e) {
			log.log(Level.WARNING, "Exception setting up logger", e);
		}

		int portNumber = 9000;
		try {
			portNumber = Integer.parseInt(args[0]);
		} catch (Throwable t) {
		}

		new Thread(new Server(portNumber)).start();
	}

	private final GameManager manager;

	private final int portNumber;

	public Server(int port) {
		portNumber = port;
		manager = new GameManager();
	}

	public void run() {
		try {
			ServerSocket socket = new ServerSocket(portNumber);
			log.info("Listening on port " + portNumber);
			log.fine("Fine!");
			log.finer("Finer!");
			log.finest("Finest!");

			while (true) {
				Socket clientSocket = null;
				try {
					clientSocket = socket.accept();
					log.info("New connection from " + clientSocket + ". Spawning handler.");
					Connection clientConn = new Connection(clientSocket);
					manager.addClientConnection(clientConn);
				} catch (IOException e) {
					log.log(Level.WARNING, "Exception initializing new client connection", e);
				}
			}

		} catch (IOException e) {
			log.log(Level.WARNING, "Exception accepting connections", e);
		}
	}
}
